package com.leff.cards.data;

import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

import android.util.Log;

import com.leff.cards.util.Secrets;
import com.leff.cards.util.Dictionary;

public class CompositeResponseCard extends AbstractCard implements Secrets {

	private ArrayList<ResponseCard> mCards;
	
	private CompositeResponseCard(ArrayList<ResponseCard> cards) {
		mCards = cards;
	}
	
	public ArrayList<ResponseCard> getResponses() {
		return mCards;
	}

	@Override
	public long getId() {
		if(mCards == null || mCards.size() == 0) {
			return 0;
		}
		return mCards.get(0).getId();
	}

	@Override
	public String getText() {
		
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for(ResponseCard RC : mCards) {
			if(!first) {
				sb.append(" / ");
			}
			sb.append(RC.getText());
			first = false;
		}
		return sb.toString();
	}
	
	public static CompositeResponseCard fromJSONArray(JSONArray arr) {
		
		ArrayList<ResponseCard> cards = new ArrayList<ResponseCard>();
		for(Object O : arr) {
			Dictionary dict = Dictionary.fromJSONObject(O);
			ResponseCard rc = ResponseCard.fromDictionary(dict);
			
			cards.add(rc);
		}
		
		return new CompositeResponseCard(cards);
	}
	
	public static CompositeResponseCard fromJSONString(String json) {
		
		JSONParser parser = new JSONParser();
		
		ArrayList<ResponseCard> cards = new ArrayList<ResponseCard>();
		
		try {
			JSONArray arr = (JSONArray)parser.parse(json);
			
			for(Object O : arr) {
				String cardJson = (String)O;
				ResponseCard rc = ResponseCard.fromJSONString(cardJson);
				
				cards.add(rc);
			}
			
		} catch(Exception e) {
			Log.v(TAG, "Error Parsing Server Response:", e);
		}
		
		return new CompositeResponseCard(cards);
	}
}
